import os
import time
from concurrent.futures import ThreadPoolExecutor

import requests


def get_m3u8(url):
    url = url + 'index.m3u8'
    res = requests.get(url)
    with open('../数据暂存/m3u8.txt', "wb") as f:
        f.write(res.content)
    print("m3u8文件下载完成")


def down_ts(url: str):
    name = url.split(r"/")[-1]
    header = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41"}
    while True:
        try:
            res = requests.get(url, headers=header)
            with open(f"../数据暂存/{name}", mode="wb") as f:
                f.write(res.content)
            print(f"{name}下载完成")
            break
        except Exception as e:
            print("name下载异常", e)
            time.sleep(3)


def download(list1):
    with open("../数据暂存/m3u8.txt", mode='r', encoding="utf-8") as f:
        for line in f:
            if line.startswith("#"):
                continue
            list1.append(line.strip())
    print(len(list1))
    with ThreadPoolExecutor(30) as t:
        for i in list1:
            t.submit(down_ts, url + i)
    print("下载完成")


def merge(lst, name):
    """合并ts文件，生成完整的mp4文件"""
    # 获取所有ts文件列表
    lst.sort()
    s = "+".join(lst)
    os.chdir("../数据暂存")
    os.system(f"copy /b {s} {name}")
    os.system(fr"move {name} E:\T\Videos\为人师表")
    print("合并成功")
    # 删除暂存数据
    # os.system("del *.ts")
    os.system("del *.txt")
    print("======Done=====")


def func(file):
    os.chdir("../数据暂存")
    with open(file, "r", encoding='utf-8') as f:
        line = f.readline()
        n = 0
        lst1 = []
        while line:
            n += 1
            name = '{}.mp4'.format(n)
            lst = []
            while len(lst) != 200 and line:
                if line.startswith("#"):
                    line = f.readline()
                    continue
                lst.append(line.strip())
                line = f.readline()
            s = "+".join(lst)
            os.system(f"copy /b {s} {name}")
            lst1.append(name)
        print("批次合并完成")
        print(lst1)
        s = "+".join(lst1)
        os.system(fr"copy /b {s} 为人师表.mp4")


def main(url, name):
    get_m3u8(url)
    lst = []
    download(lst)
    merge(lst, name)


if __name__ == '__main__':
    url = 'https://wolongzywcdn2.com:65/20220710/FQSQfoiG/'
    # main(url, "为人师表.mp4")
    func("../数据暂存/m3u8.txt")
